import store from 'store2'

const SEARCH_KEY = '__search_key___'
const MAX_LENGTH = 15
const PLAY_HISTORY_KEY = '__play_history__'
const HISTORY_MAX_LENGTH = 100
const FAVORITE_KEY = '__favorate__'
const FAVORITE_MAX_LENGTH = 200

/**
 * 插入数据到数组，数据不能重复，数组长度有限制
 * @param arr {Array}
 * @param val {Object}
 * @param compare {function}
 * @param max_len {Number}
 */
function insertArr (arr, val, compare, maxLen) {
  let fIndex = arr.findIndex(compare)
  if (fIndex === 0) {
    return
  }
  if (fIndex !== -1) {
    arr.splice(fIndex, 1)
  }
  arr.unshift(val)
  if (maxLen && maxLen < arr.length) {
    arr.pop()
  }
}

function deleteFromArray (arr, compare) {
  const index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

/**
 * 保存单条搜索历史
 * @param query {String}
 * @return {Array}
 */
export function saveSearch (query) {
  let history = store.get(SEARCH_KEY, [])
  insertArr(history, query, (item) => {
    return item === query
  }, MAX_LENGTH)
  store.set(SEARCH_KEY, history)
  return history
}

export function loadSearch () {
  return store.get(SEARCH_KEY, [])
}

/**
 * 删除localstorage中的记录
 * @param item {String}
 * @return {Array}
 */
export function deleteSearch (item) {
  let history = store.get(SEARCH_KEY, [])
  deleteFromArray(history, his => item === his)
  store.set(SEARCH_KEY, history)
  return history
}

/**
 * 删除所有搜索记录
 */
export function clearSearch () {
  store.remove(SEARCH_KEY)
}

/**
 * 获取播放历史
 * @return {Array}
 */
export function loadPlay () {
  return store.get(PLAY_HISTORY_KEY, [])
}

/**
 * 保存播放历史
 * @param song
 * @return {Array}
 */
export function savePlay (song) {
  let songs = loadPlay()
  insertArr(songs, song, item => item.id === song.id, HISTORY_MAX_LENGTH)
  store.set(PLAY_HISTORY_KEY, songs)
  return songs
}

/**
 * 获取收藏列表
 * @return {Array}
 */
export function loadFavoriteSongs () {
  return store.get(FAVORITE_KEY, [])
}

export function saveFavoriteSong (song) {
  let songs = loadFavoriteSongs()
  insertArr(songs, song, item => item.id === song.id, FAVORITE_MAX_LENGTH)
  store.set(FAVORITE_KEY, songs)
  return songs
}

export function deleteFavoriteSong (song) {
  let songs = loadFavoriteSongs()
  deleteFromArray(songs, item => item.id === song.id)
  store.set(FAVORITE_KEY, songs)
  return songs
}
